# -*- coding=utf-8 -*-
# Author: Slp
# @Date : 2021-08-26

import os
import time
import traceback

import numpy as np
from PIL import Image


def currentDate():
    '''生成当前日期字符串'''
    date = time.localtime()
    return '-'.join([str(date.tm_year), str(date.tm_mon), str(date.tm_mday)])


def currentTime():
    '''生成当前时间字符串'''
    date = time.localtime()
    # return '-'.join ([str (date.tm_hour), str (date.tm_min), str (date.tm_sec)])
    return '-'.join([str(date.tm_hour), str(date.tm_min)])


def createDir(project):
    '''创建当前日期和当前时间目录'''
    path = r"../../testfile/%s" % project
    if not os.path.exists(path):
        os.mkdir(path)
    dateDir = os.path.join(path, currentDate())
    # 如果当前日期目录不存的话就创建
    if not os.path.exists(dateDir):
        os.mkdir(dateDir)
    # timeDir = os.path.join(dateDir, currentTime())  # 需要当前时间做为文件夹名称时使用
    timeDir = os.path.join(dateDir)  # 按天的维度汇总使用
    # 如果当前时间目录不存的话就创建
    if not os.path.exists(timeDir):
        os.mkdir(timeDir)
    return timeDir


def takeScreenshot(driver, savePath, pictureName):
    picturePath = os.path.join(savePath, pictureName + '.png')
    try:
        # driver.get_screenshot_as_file(picturePath)
        # 返回网页的高度的JS代码
        new_height = driver.get_window_size()['height'] + 300  # 窗口高度
        height = 0
        driver.save_screenshot(picturePath)
        while height < new_height:
            base_mat = np.atleast_2d(Image.open(picturePath))  # 打开截图并转为二维矩阵
            for i in range(height, new_height, 400):
                if i > 0:
                    driver.execute_script(
                        "document.getElementsByClassName('ant-layout')[0].getElementsByTagName('section')[0].scrollTo(0,{})"
                            .format(i))
                    time.sleep(0.5)
                    driver.save_screenshot(f'%s_{i}.png' % picturePath)  # 保存截图
                    mat = np.atleast_2d(Image.open(f'%s_{i}.png' % picturePath))  # 打开截图并转为二维矩阵
                    base_mat = np.append(base_mat, mat, axis=0)  # 拼接图片的二维矩阵
            Image.fromarray(base_mat).save(picturePath)
            height = new_height
            time.sleep(2)

    except Exception as ex:
        print(traceback.print_exc(), str(ex))


if __name__ == '__main__':
    createDir("jyy")
